package com.yix.admin.modules.security.config;

import com.yix.admin.modules.security.config.bean.JwtSecurityProperties;
import com.yix.admin.modules.security.dto.OnlineUserDto;
import com.yix.admin.modules.security.service.OnlineUserService;
import com.yix.admin.modules.security.service.UserCacheClean;
import com.yix.common.utils.SpringContextHolder;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author wdx
 * @version 1.0
 * @Description 该类继承OncePerRequestFilter，顾名思义，它能够确保在一次请求中只通过一次filter
 * 该类使用JwtTokenUtils工具类进行token校验
 * @date 2021/1/20 14:23
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private OnlineUserService onlineUserService;
    @Autowired
    private UserCacheClean userCacheClean;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException{
        JwtSecurityProperties jwtSecurityProperties = SpringContextHolder.getBean(JwtSecurityProperties.class);
        String requestUri = request.getRequestURI();
        //获取request token
        String token = null;
        String bearerToken = request.getHeader(jwtSecurityProperties.getHeader());
        if(StringUtils.hasText(bearerToken) && bearerToken.startsWith(jwtSecurityProperties.getTokenStartWith())){
            token = bearerToken.substring(jwtSecurityProperties.getTokenStartWith().length());
            log.debug("请求" + requestUri + "携带的token值：" + token);
            OnlineUserDto onlineUserDto = null;
            boolean cleanUserCache = false;
            try {
                onlineUserDto = onlineUserService.getOne(jwtSecurityProperties.getOnlineKey() + token);
            }catch (ExpiredJwtException e){
                log.error(e.getMessage());
                cleanUserCache = true;
            }finally {
                if (cleanUserCache || Objects.isNull(onlineUserDto)) {
                    userCacheClean.cleanUserCache(String.valueOf(jwtTokenUtils.getClaims(token).get(JwtTokenUtils.AUTHORITIES_KEY)));
                }
            }
            if (onlineUserDto != null && StringUtils.hasText(token)) {
                Authentication authentication = jwtTokenUtils.getAuthentication(token);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                // Token 续期
                jwtTokenUtils.checkRenewal(token);
            }
        }else {
            log.debug("请求" + requestUri + "非法Token：{}" + bearerToken);
        }
        filterChain.doFilter(request, response);
    }
}
